<?php
namespace App\Http\Controllers;

use Dcat\Admin\Traits\HasUploadedFile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class HomeController extends Controller {
    use HasUploadedFile;


    /**
     * 自定义文件上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed|void
     */
    public function upload(Request $request) {
        $driver = $request->input('driver',env("FILESYSTEM_DRIVER", 'public'));
        $disk = Storage::disk($driver);
        $file = $request->file;
        if (empty($file)) {
            return show_error('未检测到文件');
        }
        $md5 = md5_file($file->path());//大文件消耗性能
        //$md5 = md5(unique_no("FILES_", time()));
        //同一文件不覆盖
        $exist = \App\Models\AdminAttachment::where("md5", $md5)->selectRaw("id,path,url,disk,size,type,ext")->first();
        if (!empty($exist)) {
            return show_success('上传成功',$exist);
        }
        // 获取上传的字段名称
        $ext = strtolower($file->extension());
        $allows =  [//限制文件类型 ,
            "image" => ['jpg', 'jpeg', 'png', 'bmp', 'svg', "ico", 'gif', 'webp'],
            "doc" => ['pdf', "doc", 'docx', 'xlsx', 'xls', 'ppt', 'pptx', 'cvs', 'wps', 'txt', 'md', 'rtf'],
            "video" => ['mp4', 'api', 'flv', 'mpg', 'mpeg', 'wmv', '3gp', 'rmvb', 'rm'],
            "audio" => ['mp3', 'wmv', 'amr', 'aud'],
            "file" => ['zip', 'rar', '7z','apk','ipa'],
        ];
        $dir = "";
        foreach ($allows as $key => $val) {
            if (in_array($ext, $val)) {
                $dir = $key;
            }
        }
        if ($dir === "" && isset($allows) &&!empty($allows)) {
            return $this->responseErrorMessage("不允许上传的文件类型！");
        }else if ($dir === "") {
            $dir = "file";
        }
        $path="uploads/" . $dir."s/".date("Ym");
        $newName =  $md5 . "." . $file->extension();
        try {
            $result = $file->storeAs($path,  $newName,$driver);
            if ($result) {
                $attach=new \App\Models\AdminAttachment();
                $attach->fill([
                    'platform' =>1,
                    'path' => $path.'/'.$newName,
                    'type' => $dir,
                    'url' => $disk->url($result),
                    'md5' => $md5,
                    'platform'=>$request->input("platform"),
                    'size'=>round($file->getSize()/1024,2),
                    'disk' => $driver,
                    'ext'=>$file->extension(),
                    'created_at' => date("Y-m-d H:i:s"),
                    'updated_at' => date("Y-m-d H:i:s"),
                ]);
                $attach->save();
                return show_success('上传成功',$attach);
            }else{
                return show_error('上传失败',$result);
            }
        } catch (\Excetion $e) {
            return show_error('上传失败',$e->getMessage());
        }

    }

}
